#include <pthread.h>
#include <iostream>
#include <unistd.h>
class MutexLock   
{  
public:      
    //...
    MutexLock();
    ~MutexLock();
    void lock();
    void unlock();
    pthread_mutex_t& getMutex(){
        return this->mutex;
    }
private:  
    pthread_mutex_t mutex;
};

MutexLock::MutexLock() {
    pthread_mutex_init(&mutex, nullptr);
}

MutexLock::~MutexLock(){
    pthread_mutex_destroy(&mutex);
}
void MutexLock::lock(){
    pthread_mutex_lock(&mutex);
}
void MutexLock::unlock(){
    pthread_mutex_unlock(&mutex);
}

class Condition   
{   
public:      
    //...
    void wait(MutexLock &mutexLock);
    void notify();
    void notifyall();
private:   
    pthread_cond_t cond;
};
void Condition::wait(MutexLock &mutexLock){
    pthread_cond_wait(&cond,&mutexLock.getMutex());
}
void Condition::notify() {
    pthread_cond_signal(&cond);
}
//广播情况
void Condition::notifyall(){
    pthread_cond_broadcast(&cond);
}




//共享数据
//共享数据部分
typedef struct Share_s
{
    MutexLock mutex;
    Condition cond;
}Share_t;


//test
void* threadFunc(void* arg) {

    std::cout << "Thread started." << std::endl;
    Share_t *share = (Share_t *)arg;

    share->mutex.lock();
    std::cout << "Waiting for condition..." << std::endl;
    share->cond.wait(share->mutex);
    std::cout << "Condition signal received." << std::endl;
    share->mutex.unlock();
    std::cout << "Thread finished." << std::endl;
    return nullptr;
}

int main() {
    pthread_t thread;
    Share_t share;
    
    pthread_create(&thread, nullptr, threadFunc, &share);

    // 主线程等待一段时间，然后发送条件信号给子线程
    sleep(2);
    share.mutex.lock();
    std::cout << "Sending condition signal..." << std::endl;
    share.mutex.unlock();
    share.cond.notify();
    pthread_join(thread, nullptr);

    return 0;
}
